package com.neuedu.controller;

import com.alibaba.fastjson2.JSON;
import com.neuedu.model.Comment;
import com.neuedu.model.Product;
import com.neuedu.service.ProductService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.persistence.Entity;
import java.util.List;

@Slf4j
@RestController
@Component
@Entity
@Controller
public class ProductController {

    @Autowired
    private ProductService productService;

    @RequestMapping("/product/{pid}")
    @GetMapping
    public Product getProductById(@PathVariable("pid") Integer pid){
        log.info("查看{}商品信息",pid);
        Product product = productService.queryProductById(pid);
        log.info("商品信息查询成功，内容为：{}", JSON.toJSONString(product));
        return product;
    }
    @RequestMapping("/product/api1/demo1")
    public String api1Demo1() {
        return "api1-demo1";
    }

    @RequestMapping("/product/api1/demo2")
    public String api1Demo2() {
        return "api1-demo2";
    }

    @RequestMapping("/product/api2/demo1")
    public String api2Demo1() {
        return "api2-demo1";
    }

    @RequestMapping("/product/api2/demo2")
    public String api2Demo2() {
        return "api2-demo2";
    }



    //商品信息管理-添加功能
//    @PostMapping("/product/{pid}")
//    public String addProduct(@RequestBody Product product) {
//        productService.addProduct(product);
//        return "Product added successfully";
//    }
    // 减少库存
    @PostMapping("/product/reduceStock/{pid}/{quantity}")
    public String reduceStock(@PathVariable("pid") Integer pid, @PathVariable("quantity") Integer quantity) {
        boolean result = productService.reduceStock(pid, quantity);
        if (result) {
            return "Stock reduced successfully";
        } else {
            return "Stock reduction failed, insufficient stock";
        }
    }

    // 查询商品库存
    @GetMapping("/product/stock/{pid}")
    public Integer getStockById(@PathVariable("pid") Integer pid) {
        return productService.getStockById(pid);
    }

    // 添加商品评价
    @PostMapping("/product/comment")
    public String addComment(@RequestBody Comment comment) {
        productService.addComment(comment);
        return "商品评价添加成功";
    }

    // 查询商品的所有评价
    @GetMapping("/product/comment/{pid}")
    public List<Comment> getCommentsByProductId(@PathVariable("pid") Integer pid) {
        return productService.getCommentsByProductId(pid);
    }



}
